import { AnyEvent, EventMetaData } from "@atrilabs/forest";
import { BrowserForestManager } from "./BrowserForestManager";
import { BrowserClient } from "../types";

/**
 * createAPI is responsible to keep BrowserForestManager & backend in sync.
 * This module will be part of frontend bundle.
 * @param client
 */
function createAPI(client: BrowserClient) {
  function postNewEvents(
    forestPkgId: string,
    pageId: string,
    data: {
      name: string;
      events: AnyEvent[];
      meta: EventMetaData;
    }
  ) {
    const forest = BrowserForestManager.getForest(forestPkgId, pageId);
    if (forest) {
      forest.handleEvents(data);
      const { events } = data;
      events.forEach((event) => {
        client.postNewEvent(forestPkgId, pageId, event, (success) => {
          if (!success) {
            console.log("Failed to send event to backend");
          }
        });
      });
    }
  }
  return { ...client, postNewEvents };
}

/**
 * Following line will be generated by a loader
 * import Client from "some-client";
 * And the declare statement below will be replaced with this import statement.
 */
declare var client: BrowserClient;

export default createAPI(client);
